package org.opens.db.column.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.opens.db.JdbcUtil;
import org.opens.db.column.entity.ColumnEntity;
import org.opens.db.column.entity.TableEntity;
import org.opens.db.column.service.I_DbInfoService;
import org.opens.exception.BusinessException;
import org.opens.util.DatabaseConnectInfoEntity;

import java.util.List;

/**
 * 新改了jdbc工具, 这个类下的方法需要调试
 */
public class IDbInfoServiceOfOracle implements I_DbInfoService {

    private static Log log = LogFactory.get(IDbInfoServiceOfOracle.class);

    private static final String typeMappingPath = "mapping\\ORACLE.json";

    @Override
    public List<TableEntity> getAllTables(DatabaseConnectInfoEntity databaseConnectInfo) {
        return null;
    }

    @Override
    public List<ColumnEntity> getAllColumn(DatabaseConnectInfoEntity databaseConnectInfo) {
        // 最后必须有一个空格, 否则会报错: java.sql.SQLSyntaxErrorException: ORA-00933: SQL 命令未正确结束
        return JdbcUtil.query(
                databaseConnectInfo,
                ColumnEntity.class,
                "SELECT t1.table_name, t1.COLUMN_NAME, t1.data_type, t1.DATA_LENGTH, t1.NULLABLE, t2.comments, listagg(uc.constraint_type, ',') WITHIN GROUP(ORDER BY t1.table_name) tab_index FROM user_tab_columns t1 LEFT JOIN user_col_comments t2 ON t1.table_name = t2.TABLE_NAME AND t1.COLUMN_NAME = t2.COLUMN_NAME LEFT JOIN user_cons_columns cc ON cc.table_name = t1.table_name AND cc.column_name = t1.column_name LEFT JOIN user_constraints uc ON t1.table_name = uc.table_name AND uc.constraint_name = cc.constraint_name WHERE t1.table_name = ? GROUP BY t1.table_name, t1.COLUMN_NAME, t1.data_type, t1.DATA_LENGTH, t1.NULLABLE, t2.comments ",
                databaseConnectInfo.getTableName()
                );
    }

    @Override
    public TableEntity getTableInfo(DatabaseConnectInfoEntity databaseConnectInfo) {
        List<TableEntity> tableEntities = JdbcUtil.query(
                databaseConnectInfo,
                TableEntity.class,
                "SELECT table_name, comments FROM user_tab_comments WHERE table_name = ? ",
                databaseConnectInfo.getTableName()
        );

        if (CollectionUtil.isEmpty(tableEntities)) {
            throw new BusinessException("未查询到table_name为" + databaseConnectInfo.getTableName() + "的有效数据.");
        }

        return tableEntities.get(0);
    }

}
